package com.yumeng.framework.auth.shiro.helper;

import com.yumeng.common.helper.AssertHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.crypto.hash.SimpleHash;

import static org.apache.shiro.lang.util.ByteSource.Util.bytes;

/**
 *
 * @author wxd
 * @date 2025/9/26 16:30
 */
@Slf4j
public class PasswordHelper {

    public static int hashIterations = 10;

    //123456-eWhnK0NFWG9UaGhwZzBhQTgwUzlYZz09-73q+lTbTKvL61Igg7MjnpSXHHTbQKT4HXp+1hPYZKxw=
    //123457-c2RXY2ZKc3dudC90eENGU0krTGhzZz09-dVZx2dNDEFFLCrypMwMRMZUktrsq0Xtq41dnX0xzL2I=

    public static HashedCredentialsMatcher createHashedCredentialsMatcher(){
        HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
        credentialsMatcher.setHashAlgorithmName(Sha256Hash.ALGORITHM_NAME);  // 散列算法，这里使用更安全的sha256算法
        credentialsMatcher.setStoredCredentialsHexEncoded(false);  // 数据库存储的密码字段使用HEX还是BASE64方式加密
        credentialsMatcher.setHashIterations(PasswordHelper.hashIterations);  // 散列迭代次数
        return credentialsMatcher;
    }

    public static String encryptPassword(String pwd, String salt) {
        AssertHelper.assertArrayNotBlank("pwd、salt不能为空", pwd, salt);
        String newPassword = new SimpleHash(Sha256Hash.ALGORITHM_NAME, pwd, bytes(salt), hashIterations).toBase64();
        return newPassword;
    }

    /**
     * 16进制编码速度明显快，但体积要大，base64相对慢些，编码后相对较小
     * @return
     */
    public static String createSalt(){
        SecureRandomNumberGenerator secureRandomNumberGenerator = new SecureRandomNumberGenerator();
        return bytes(secureRandomNumberGenerator.nextBytes().toBase64()).toBase64();
    }

    public static void main(String[] args){
        //String salt = createSalt();
        //log.debug("salt:{}-{}", salt.length(), salt);

        String pwd = encryptPassword("123321", "123321");
        log.info("pwd:{}", pwd);
    }

}
